package cas.ihep.hep.util;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;

public class LLVMInvoker implements Closeable {

    private static boolean inited=false;
    private static LLVMInvoker ins=null;
    private Context polyglot;
    private Value main;

    public LLVMInvoker(String file) throws IOException {
        polyglot= Context.newBuilder().allowAllAccess(true).build();
        Source src= Source.newBuilder("llvm",new File(file)).build();
        main=polyglot.eval(src);
    }

    public static LLVMInvoker instance(String file)throws IOException{
        if(!inited){
            synchronized (LLVMInvoker.class){
                if(!inited) {
                    ins = new LLVMInvoker(file);
                    Runtime.getRuntime().addShutdownHook(new Thread(){
                        public void run(){
                            ins.close();
                        }
                    });
                    inited=true;
                }
            }
        }
        return ins;
    }

    public void invoke(String funcname,Object ... params){
        main.getMember(funcname).execute(params);
    }

    @Override
    public void close() {
        polyglot.close();
    }
}
